<template>
  <view class="xen-app-selector">
    <picker
      class="selector-picker"
      mode="selector"
      :range="displayRange"
      :value="currentIndex"
      :disabled="disabled"
      @change="handleChange"
      @cancel="handleCancel"
    >
      <view 
        class="selector-display" 
        :class="{ 
          'has-value': hasValue, 
          'disabled': disabled,
          'has-error': hasError 
        }"
      >
        <view class="selector-content">
          <text class="selector-text" :class="{ 'placeholder': !hasValue }">
            {{ displayText }}
          </text>
          <uni-icons 
            type="down" 
            size="16" 
            :color="disabled ? '#ccc' : hasError ? '#ff5252' : '#999'"
          ></uni-icons>
        </view>
      </view>
    </picker>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';

interface SelectorOption {
  value: any;
  text: string;
  [key: string]: any;
}

interface Props {
  // 选项数据
  options?: string[] | SelectorOption[];
  // 当前选中的值
  modelValue?: any;
  // 占位符
  placeholder?: string;
  // 是否禁用
  disabled?: boolean;
  // 是否有错误
  hasError?: boolean;
  // 选项的文本字段名（当options为对象数组时使用）
  optionTextField?: string;
  // 选项的值字段名（当options为对象数组时使用）
  optionValueField?: string;
}

const props = withDefaults(defineProps<Props>(), {
  options: () => [],
  modelValue: '',
  placeholder: '请选择',
  disabled: false,
  hasError: false,
  optionTextField: 'text',
  optionValueField: 'value',
});

const emit = defineEmits<{
  (e: 'update:modelValue', value: any): void;
  (e: 'change', value: any, option?: SelectorOption | string): void;
  (e: 'cancel'): void;
}>();

// 当前选中的索引
const currentIndex = ref(0);

// 判断选项是否为对象数组
const isObjectArray = computed(() => {
  return props.options.length > 0 && typeof props.options[0] === 'object';
});

// 获取用于picker显示的文本数组
const displayRange = computed(() => {
  if (isObjectArray.value) {
    return (props.options as SelectorOption[]).map(
      (item) => item[props.optionTextField] || ''
    );
  }
  return props.options as string[];
});

// 判断是否有值
const hasValue = computed(() => {
  return props.modelValue !== undefined && 
         props.modelValue !== null && 
         props.modelValue !== '';
});

// 显示的文本
const displayText = computed(() => {
  if (!hasValue.value) {
    return props.placeholder;
  }

  if (isObjectArray.value) {
    const option = (props.options as SelectorOption[]).find(
      (item) => item[props.optionValueField] === props.modelValue
    );
    return option ? option[props.optionTextField] : props.placeholder;
  }

  return props.modelValue;
});

// 监听modelValue变化，更新currentIndex
watch(
  () => props.modelValue,
  (newValue) => {
    updateCurrentIndex(newValue);
  },
  { immediate: true }
);

// 监听options变化，更新currentIndex
watch(
  () => props.options,
  () => {
    updateCurrentIndex(props.modelValue);
  },
  { deep: true }
);

// 更新当前索引
const updateCurrentIndex = (value: any) => {
  if (!value || props.options.length === 0) {
    currentIndex.value = 0;
    return;
  }

  let index = 0;
  if (isObjectArray.value) {
    index = (props.options as SelectorOption[]).findIndex(
      (item) => item[props.optionValueField] === value
    );
  } else {
    index = (props.options as string[]).indexOf(value);
  }

  currentIndex.value = index >= 0 ? index : 0;
};

// 处理选择变化
const handleChange = (e: any) => {
  const index = e.detail.value;
  currentIndex.value = index;

  let value: any;
  let option: SelectorOption | string | undefined;

  if (isObjectArray.value) {
    const selectedOption = (props.options as SelectorOption[])[index];
    value = selectedOption ? selectedOption[props.optionValueField] : '';
    option = selectedOption;
  } else {
    value = (props.options as string[])[index] || '';
    option = value;
  }

  emit('update:modelValue', value);
  emit('change', value, option);
};

// 处理取消
const handleCancel = () => {
  emit('cancel');
};
</script>

<style lang="scss" scoped>
.xen-app-selector {
  width: 100%;

  .selector-picker {
    width: 100%;
  }

  .selector-display {
    width: 100%;
    min-height: 42px;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    background-color: #ffffff;
    transition: all 0.3s ease;
    box-sizing: border-box;

    &.has-value {
      border-color: #d9d9d9;
    }

    &.has-error {
      border-color: #ff5252;
      background-color: #fff8f8;
    }

    &.disabled {
      background-color: #f5f5f5;
      border-color: #d9d9d9;
      opacity: 0.6;
    }

    &:active:not(.disabled) {
      background-color: #f9fafb;
      border-color: #7881de;
    }

    .selector-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 12px;
      min-height: 42px;
      box-sizing: border-box;

      .selector-text {
        flex: 1;
        font-size: 14px;
        color: #333;
        line-height: 1.5;
        word-break: break-all;
        padding: 8px 0;

        &.placeholder {
          color: #999;
        }
      }

      .uni-icons {
        flex-shrink: 0;
        margin-left: 8px;
      }
    }
  }

  // 禁用状态下的文本颜色
  .disabled .selector-text {
    color: #999 !important;
  }
}
</style>

